<?php
/**
 * This interface will handle document deletion 
 * for Medical Study,or Medical Center, or Patient
 * 
 */

use Nawa\MedicalStudy\MedicalCenter;
use Fox\Behaviors;
use Fox\Generator;
use Nawa\Document;
$xview = Xview::instance();
$msid = $xview->val('msid');
$mcid = $xview->val('mcid');
$patientid = $xview->val('patientid');
$confirmation = $xview->val('confirmation',false);
$docid = $xview->val('docid');

$title =  Msg(Nawa\Messages::BUNDLE,Nawa\Messages::DOCUMENT_DELETION_TITLE);

if(empty($docid)) {
	// Not possible display an error message
	Fox\Message::Error(Msg(Nawa\Messages::BUNDLE,Nawa\Messages::ERR_DOCUMENT_NOT_FOUND));
} else {
	try {
		$document = Fox\Dao::load(Document::className(),$docid);
		$message = Msg(Nawa\Messages::BUNDLE,Nawa\Messages::DOCUMENT_DELETION_CONFIRMATION,$document->filename);
	} catch(Fox\Object\Exception\NotExist $e) {
		Fox\Message::Error($e);
	}
}

// We are dealing with a 
if(!Fox\Message::errors() && $confirmation) {
	try {
		if(!empty($patientid)) {
			// Delete a Patient Document
			
		} elseif(!empty($mcid)) {
			// Delete a Medical Center Document
			$documentLink = Fox\Dao::load(MedicalCenter\Document::className(),$msid.':'.$mcid.':'.$docid);
			$documentLink->delete();
			$document->delete();
			
		} elseif(!empty($msid)) {
			// Delete a Medical Study Document
		}
		Fox\Message::Success(Msg(Nawa\Messages::BUNDLE,Nawa\Messages::DOCUMENT_DELETION_SUCCESS));
	} catch(Fox\Object\Exception\Save $e) {
		Fox\Message::Error($e);
	} catch(Fox\Object\Exception\NotExist $e) {
		Fox\Message::Error($e);
	}
	echo $xview->messages(true,true);
	exit;
}
if(!Fox\Message::errors()) {
	$callback = Generator::ajaxReload('MC_documents',null,'');
	$link1 = Generator::ajax(Generator::url('medicalstudies','documents','delete',
								array('msid' => $msid,
									'mcid' => $mcid,
									'patientid' => $patientid,
									'docid' => $docid)), '&confirmation=true', $callback);
	$popup = new Fox\Popup\ToConfirm('docDeletion',$title,$message,$link1);
	$popup->footer()->item(Fox\Popup\ToConfirm::ACTION_YES)->behaviors(Behaviors::value('close'));
} else {
	$message = $xview->messages(true);
	$popup = new Fox\Popup\Help('docDeletion',$title,$message);
}
echo $popup->display();

